﻿/**
* ...
* @author Default
* @version 0.1
*/

package bdz.cms.core{
	
	import bdz.cms.core.events.CMSEvent;
	import bdz.cms.vo.*;
	import bdz.common.events.XMLLoaderEvent;
	import bdz.common.model.XMLLoader;
	
	import flash.events.EventDispatcher;
	import flash.net.URLVariables;
	
	public class CMSCore extends EventDispatcher {
		
		private var configuration:CMSConfig;
		private var dformat:String = "xml";
		function CMSCore(config:CMSConfig):void {
			configuration = config;
		}
		protected function processData(evt:String, vars:URLVariables):void {
			var xm:XMLLoader = new XMLLoader(evt);
			vars.responseFormat = dformat;
			xm.addEventListener(evt, convertResults, false, 0, true);
			xm.location = configuration.baseURL+configuration.scriptPage;
			xm.send(vars);
			xm = null;
			dispatchEvent(new CMSEvent(CMSEvent.PROCESSING_START, evt));
		}
		private function handleDataLoad(xmres:XMLList, evtype:String):void {
			var results:Array = new Array();
			for each(var xm:XML in xmres) {
				results.push(getNativeData(evtype, xm));
			}
			
			dispatchEvent(new CMSEvent(evtype, results));
		}
		private function getNativeData(evt:String, topush:*):* {
			switch(CMSEvent.typeCheck(evt)) {
				case "media":
					return new MediaVO(topush);
				
				case "content":
					return new ContentVO(topush);
				
				case "category":
					return new CategoryVO(topush);
				
				case "login":
					return new UserVO(topush);
			}
			return topush;
		}
		private function convertResults(evt:XMLLoaderEvent):void {
			trace(evt.data);
			var xmres:XMLList = new XML(evt.data).data;
			handleDataLoad(xmres, evt.type);
			dispatchEvent(new CMSEvent(CMSEvent.PROCESSING_END, evt.type));
			
		}
		public function set responseFormat(s:String):void{
			dformat = s;
		}
		public function get responseFormat():String{
			return dformat;
		}
		
	}
	
}